package com.corpgovernment.common.bo;

import com.corpgovernment.common.holder.TenantContextHolder;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
public class ReplaceSupplierUidBo {

    /**
     * 供应商信息集合
     */
    private List<Supplier> suppliers;

    @Data
    public static class Supplier{
        /**
         * 供应商uid
         */
        private String supplierUid;
        /**
         * 供应商公司id
         */
        private String supplierCorp;
    }

    /**
     * 根据租户获取供应商公司信息
     * @return
     */
    public static List<Supplier> getReplaceSupplierUidBo(){
        Config config = ConfigService.getConfig("corpgovernment.common");
        String replaceSupplier = config.getProperty("replaceSupplierUid", "");

        if (StringUtils.isBlank(replaceSupplier)){
            return Collections.emptyList();
        }

        JsonNode tree = JsonUtils.getJsonNode(replaceSupplier);
        JsonNode node = tree.get(TenantContextHolder.getTenantId());
        if (Objects.isNull(node)){
            return Collections.emptyList();
        }

        ReplaceSupplierUidBo replaceSupplierUidBo = JsonUtils.parse(node.toString(), ReplaceSupplierUidBo.class);

        if (Objects.isNull(replaceSupplierUidBo) || CollectionUtils.isEmpty(replaceSupplierUidBo.getSuppliers())){
            return Collections.emptyList();
        }

        return replaceSupplierUidBo.getSuppliers();
    }

    /**
     * 历史订单号数据
     */
    public static Map<String, String> getHistoryOrderMap(){
        Config config = ConfigService.getConfig("corpgovernment.common");
        String historyOrder = config.getProperty("openCardHistoryOrder", "");

        if (StringUtils.isBlank(historyOrder)){
            return Collections.emptyMap();
        }

        Map<String, String> historyOrderMap = Arrays.stream(historyOrder.split(",")).collect(Collectors.toMap(item -> item, Function.identity(), (k1, k2) -> k1));
        return historyOrderMap;
    }
}
